package org.zavgame.ejb;

import javax.annotation.PostConstruct;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.apache.openejb.util.LogCategory;
import org.apache.openejb.util.Logger;

/**
 * OpenEJB interceptor for logging IN/OUT Player data.
 * 
 * @author alexey
 *
 */
public class PlayerLogInterceptor
{

   private Logger LOG = Logger.getInstance(LogCategory.OPENEJB.createChild("ZAVGAME"),
      PlayerLogInterceptor.class.getName());

   /**
    * Logging data on every request.
    * 
    * @param ic
    * @return
    * @throws Exception
    */
   @AroundInvoke
   protected Object businessMethodInterceptor(InvocationContext ic) throws Exception
   {
      if (ic.getTarget() instanceof Players)
      {
         if (ic.getParameters() != null && ic.getParameters().length > 0)
         {
            if (ic.getParameters()[0] instanceof PlayerRequest)
            {
               PlayerRequest pr = (PlayerRequest)ic.getParameters()[0];
               LOG.info(ic.getTarget().getClass().getSimpleName() + ": method=" + ic.getMethod().getName() + ", "
                  + pr.toString());
            }
            else
            {
               // not the PlayerRequest parameter instance
               LOG.info(ic.getTarget().getClass().getSimpleName() + ": method=" + ic.getMethod().getName() + ", "
                  + ic.getParameters()[0] + " is not instanceof PlayerRequest");
            }
         }
         else
         {
            // the parameters is null or empty
            LOG.info(ic.getTarget().getClass().getSimpleName() + ": method=" + ic.getMethod().getName()
               + ", parameters is null");
         }

      }

      Object result = ic.proceed();
      LOG.info(ic.getTarget().getClass().getSimpleName() + ": method=" + ic.getMethod().getName() + ", "
         + result.toString());
      return result;
   }

   @PostConstruct
   protected void postConstructInterceptor(InvocationContext ic) throws Exception
   {
      ic.proceed();
   }
}
